package com.stylefeng.guns.modular.customer.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.customer.dao.AreaDao;
import com.stylefeng.guns.modular.customer.dao.CustomerCompanyDao;
import com.stylefeng.guns.modular.customer.service.*;
import com.stylefeng.guns.modular.customer.transfer.CustomerCompanyXlsM;
import com.stylefeng.guns.modular.system.dao.CustomerCompanyMapper;
import com.stylefeng.guns.modular.system.dao.DeptMapper;
import com.stylefeng.guns.modular.system.dao.DictMapper;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.CustomerCompany;
import com.stylefeng.guns.modular.system.model.CustomerCompanyManage;
import com.stylefeng.guns.modular.system.model.Dict;
import com.vip.vjtools.vjkit.number.NumberUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.ValidationException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 企业客户 服务实现类
 * </p>
 *
 * @author yinjc123
 * @since 2018-04-02
 */
@Service
public class CustomerCompanyServiceImpl extends ServiceImpl<CustomerCompanyMapper, CustomerCompany> implements ICustomerCompanyService {

    @Autowired
    private ICustomerCompanyManageService customerCompanyManageService;
    @Autowired
    private CustomerCompanyDao customerCompanyDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IPayPlanService payPlanService;

    @Autowired
    private ISaleService saleService;

    @Autowired
    private IPurchaseService purchaseService;

    @Autowired
    private IVisitService visitService;

    @Autowired
    private IContactService contactService;


    @Autowired
    private ICustomerRelationService customerRelationService;

    @Override
    @Transactional
    public void insert(CustomerCompany customerCompany, CustomerCompanyManage manage) {
        insert(customerCompany);
        manage.setCustomerCompanyId(customerCompany.getId());
        this.customerCompanyManageService.insert(manage);
    }


    @Override
    public boolean insert(CustomerCompany entity) {
        if (null != customerCompanyDao.customerCompanyExisted(null, entity.getUnifiedSocialCreditCode(), entity.getMilitaryCode())) {
            throw new GunsException(HttpStatus.BAD_REQUEST.value(), "该客户：\"" + entity.getName() + "\"的统一社会信用代码、军工代码必须唯一");
        }
        return super.insert(entity);
    }

    @Override
    public boolean updateById(CustomerCompany entity) {
        if (null != customerCompanyDao.customerCompanyExisted(entity.getId(), entity.getUnifiedSocialCreditCode(), entity.getMilitaryCode())) {
            throw new GunsException(HttpStatus.BAD_REQUEST.value(), "该客户：\"" + entity.getName() + "\"的统一社会信用代码、军工代码必须唯一");
        }
        return super.updateById(entity);
    }

    @Transactional
    @Override
    public void insertXlsList(List<CustomerCompanyXlsM> xlsMList) {
        for (CustomerCompanyXlsM xlsM : xlsMList) {
            if (null != customerCompanyDao.customerCompanyExisted(null, xlsM.getUnifiedSocialCreditCode(), xlsM.getMilitaryCode())) {
                throw new ValidationException("该客户：\"" + xlsM.getName() + "\"的统一社会信用代码、军工代码必须唯一");
            }
        }

        consummate(xlsMList);

        for (CustomerCompanyXlsM xlsM : xlsMList) {
            CustomerCompany customerCompany = new CustomerCompany();
            CustomerCompanyManage customerCompanyManage = new CustomerCompanyManage();
            BeanKit.copyProperties(xlsM, customerCompanyManage);
            BeanKit.copyProperties(xlsM, customerCompany);
            customerCompanyManage.setCustomerNum(NumberUtil.toInt(xlsM.getCustomerNum(), 0));
            customerCompanyManage.setProviderNum(NumberUtil.toInt(xlsM.getProviderNum(), 0));
            customerCompanyManage.setAnnualIncome(strChangeBigDecimal(xlsM.getAnnualIncome()));
            customerCompanyManage.setAnnualPurchaseAmount(strChangeBigDecimal(xlsM.getAnnualPurchaseAmount()));
            super.insert(customerCompany);
            customerCompanyManage.setCustomerCompanyId(customerCompany.getId());
            this.customerCompanyManageService.insert(customerCompanyManage);
        }
    }

    private BigDecimal strChangeBigDecimal(String string) {
        if (string == null || string == "") {
            return new BigDecimal(0);
        }
        return new BigDecimal(string);
    }

    @Override
    public List<CustomerCompany> getRelations(Integer id) {
        Set<Long> relationCustomerIds = customerRelationService.getRelationCustomerIds(id);
        if (CollectionUtils.isEmpty(relationCustomerIds)) {
            return Collections.EMPTY_LIST;
        }
        return customerCompanyDao.getCustomerCompanies(relationCustomerIds);
    }

    public void consummate(List<CustomerCompanyXlsM> customerCompanyXlsMS) {
        for (CustomerCompanyXlsM customerCompanyXlsM : customerCompanyXlsMS) {
            setAreaId(customerCompanyXlsM);
            setCustomerTypeIdByName(customerCompanyXlsM);
            setDepartIdByName(customerCompanyXlsM);
            setSaleIdByName(customerCompanyXlsM);
        }
    }

    private void setAreaId(CustomerCompanyXlsM customerCompanyXlsM) {
        String[] areaArr = customerCompanyXlsM.getArea().split("/");
        String area = areaArr[areaArr.length - 1];
        Integer areaId = areaDao.selectIdByName(area);
        if (areaId == null) {
            throw new ValidationException("该区域：" + customerCompanyXlsM.getArea() + ", 不存在！");
        }
        customerCompanyXlsM.setAreaId(areaId);
    }


    private void setCustomerTypeIdByName(CustomerCompanyXlsM xlsM) {
        String customerType = xlsM.getCustomerType();
        Dict parentDict = dictMapper.selectByNum("customer_type");
        Dict dict = dictMapper.selectByPidAndName(parentDict.getId(), customerType);
        if (dict != null) xlsM.setCustomerTypeCode(dict.getNum());
        else throw new ValidationException("该客户类型：" + customerType + "，不存在");
    }


    private void setDepartIdByName(CustomerCompanyXlsM customerCompanyXlsM) {
        String departName = customerCompanyXlsM.getDepartName();
        Integer departId = deptMapper.selectDepartIdByName(departName);
        if (departId == null) {
            throw new ValidationException("该部门：" + customerCompanyXlsM.getDepartName() + "，不存在");
        }
        customerCompanyXlsM.setDepartId(departId);
    }

    private void setSaleIdByName(CustomerCompanyXlsM customerCompanyXlsM) {
        String salesmanName = customerCompanyXlsM.getSalesmanName();
        Integer salesmanId = userMapper.selectSalesmanIdByNameAndDeptId(salesmanName, customerCompanyXlsM.getDepartId());
        if (salesmanId == null) {
            throw new ValidationException("该人员：" + customerCompanyXlsM.getSalesmanName() + "，不存在");
        }
        customerCompanyXlsM.setSalesmanId(salesmanId);
    }

    @Override
    public boolean deleteById(Serializable id) {
        payPlanService.deleteByCustomerCompanyId((Integer) id);
        saleService.deleteByCustomerCompanyId((Integer) id);
        purchaseService.deleteByCustomerCompanyId((Integer) id);
        visitService.deleteByCustomerCompanyId((Integer) id);
        customerCompanyManageService.deleteById(id);
        contactService.deleteByCustomerCompanyId((Integer) id);
        return super.deleteById(id);
    }
}
